package presentation.frame;

import presentation.redesign.*;
import rmiClient.*;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JTextPane;

import data.entity.*;
import javax.swing.JScrollPane;
import javax.swing.JButton;

import bl.service.FtPrintsService;
import bl.service.JournalService;
import bl.service.SearchSpotService;
import bl.service.TransmitFile;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.rmi.RemoteException;
import java.util.ArrayList;

public class AddJournalPane extends Panel {
	private JTextField textField;
	private JTextField textField_1;
	private UserEntity ue;
	private StringBuffer buffer = new StringBuffer(); // buffer to store image
	private JournalEntity je = new JournalEntity();
	private ArrayList<File> image = new ArrayList<File>();
	private StringBuffer mp3Path = new StringBuffer();
	private StringBuffer rmvbPath = new StringBuffer();
	private Client client = new Client();
	private JournalService js = client.getJournalService();
	private TransmitFile tf = client.getTransmitFile();
	private JTextArea jta = new JTextArea();
	private JFileChooser fileChooser = new JFileChooser();
	private String mp3Name;
	private String rmvbName;
	private SearchSpotService ss = client.getSearchSpotService();
	private JPanel annex;
	private int countAnnex = 0;

	public AddJournalPane(UserEntity ue) {
		this.ue = ue;
		JLabel title_label = new Label("标题");
		title_label.setBounds(57, 25, 54, 29);
		add(title_label);

		textField = new JTextField();
		textField.setBounds(140, 30, 196, 21);
		add(textField);
		textField.setColumns(20);

		JLabel route_label_1 = new Label("路线");
		route_label_1.setBounds(57, 88, 54, 15);
		add(route_label_1);

		/** get the route of the journal */
		textField_1 = new JTextField();
		textField_1.setBounds(140, 82, 897, 21);
		add(textField_1);
		textField_1.setColumns(50);

		JLabel context_label_5 = new Label("文字内容");
		context_label_5.setBounds(57, 179, 103, 15);
		add(context_label_5);
		//

		JScrollPane scrollPane = new JScrollPane(jta);
		scrollPane.setBounds(57, 228, 680, 203); // ////
		add(scrollPane);

		Button btnNewButton = new Button("确定");
		btnNewButton.setBounds(944, 453, 93, 23);
		add(btnNewButton);

		btnNewButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				sure();
			}
		});

		Button button = new Button("添加音频");
		button.setBounds(457, 176, 113, 23);
		add(button);
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				insertMp3();
			}
		});

		Button btnNewButton_1 = new Button("添加视频");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		btnNewButton_1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				insertRmvb();
			}
		});

		btnNewButton_1.setBounds(297, 176, 113, 23);
		add(btnNewButton_1);

		Button button_1 = new Button("添加图片");
		button_1.setBounds(140, 176, 113, 23);
		add(button_1);
		jta.setBounds(59, 211, 978, 201);

		JLabel label = new JLabel("例： 北京-上海-苏州");
		label.setBounds(140, 125, 134, 15);
		add(label);
		// add(jta);
		/** get image path */
		button_1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				insertImage();
			}
		});

		/** the show of pictures added */
		annex = new JPanel();
		annex.setLayout(null);
		// annex.setBounds(780, 228, 260, 203);
		JScrollPane annexSp = new JScrollPane(annex);
		annexSp.setBounds(780, 228, 260, 203); // ////
		annex.setPreferredSize(new Dimension(230, 800));
		add(annexSp);
		annex.setBackground(Color.WHITE);
	}

	private void addLabel(File file) {
		final Label insert = new Label(file.getName());
		annex.add(insert);
		insert.setBounds(0, 0 + countAnnex * 25, 160, 20);
		final Button delete = new Button("刪除");
		delete.setBounds(160, 0 + countAnnex * 25, 70, 20);
		delete.setForeground(Color.red);
		annex.add(delete);
		countAnnex++;
		delete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String name = insert.getText();
				if (name.substring(name.length() - 3).equals("jpg")
						|| name.substring(name.length() - 3).equals("png")) {
					String[] tmp = buffer.toString().split("/");
					buffer = new StringBuffer();
					for (int i = 0; i < tmp.length; i++) {
						if (!tmp[i].equals(name))
							buffer.append(tmp[i] + "/");
					}

				} else if (name.substring(name.length() - 3).equals("avi")) {
					rmvbName = new String();
					rmvbPath = new StringBuffer();
				} else if (name.substring(name.length() - 3).equals("mp3")) {
					mp3Name = new String();
					mp3Path = new StringBuffer();
				}
				annex.remove(delete);
				annex.repaint();
				insert.setText("已删除附件");
			}
		});
	}

	private void insertMp3() {
		if (mp3Path.length() != 0) {
			JOptionPane.showMessageDialog(null, "只能添加一个音频");
		} else {
			File file = showPath();
			if (file != null) {
				String temp = file.getName().substring(
						file.getName().length() - 3);
				if (temp.equals("mp3")) {
					mp3Path.append(file.getAbsolutePath()); // 显示音频
					mp3Name = file.getName();
					addLabel(file);

				} else
					JOptionPane.showMessageDialog(null, "音频格式不支持");
			}
		}
	}

	private void insertRmvb() {
		if (rmvbPath.length() != 0) {
			JOptionPane.showMessageDialog(null, "只能添加一个视频");
		} else {
			File file = showPath();
			if (file != null) {
				String temp = file.getName().substring(
						file.getName().length() - 3);
				if (temp.equals("avi")) {
					rmvbPath.append(file.getAbsolutePath()); // 显示音频
					rmvbName = file.getName();
					addLabel(file);
				} else
					JOptionPane.showMessageDialog(null, "视频格式不支持");

			}

		}
	}

	private void insertImage() {

		File f = showPath();
		//image.add(f);
		if (f != null) {
			// System.out.println(f.getName());
			//System.out.println(f.getName().substring(f.getName().length() - 3));
			String temp = f.getName().substring(f.getName().length() - 3);
			// System.out.println(temp.length);
			if (temp.equals("jpg") || temp.equals("png")) {
				boolean exist=false;
				for(int i=0;i<image.size();i++){
					if(image.get(i).getName().equals(f.getName())){
						exist=true;
					}
				}
				if(exist){
					JOptionPane.showMessageDialog(null, "不能添加重复图片");
					
				}
				else{
					image.add(f);
					buffer.append(f.getName() + "/");
				addLabel(f);
				}
			} else
				JOptionPane.showMessageDialog(null, "视频格式不支持");
		}
	}

	private void sure() {
		if (textField.getText().trim().equals("")
				|| textField_1.getText().trim().equals("")
				|| jta.getText().trim().equals("")){
			JOptionPane.showMessageDialog(null, "内容不能为空");
		}
		else {
		je.setImage(buffer.toString());
		je.setText(jta.getText());
		je.setTitle(textField.getText());
		je.setUserid(ue.getId());
		je.setMp3(mp3Name);
		je.setRmvb(rmvbName);

		/** route choose ? input */

		String tmp = textField_1.getText();
		String[] route = tmp.split("-");
		ArrayList<String> routeList = new ArrayList<String>();
		boolean exist = true;
		ArrayList<Integer> city = new ArrayList<Integer>();

		for (int i = 0; i < route.length; i++) {
			try {
				exist = ss.isCityExist(route[i]);
				if (!exist) {
					JOptionPane.showMessageDialog(null, route[i] + "不存在");
					break;
				}
				routeList.add(route[i]);
				city.add(ss.searchCity(route[i]).getCityID());

			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (exist) {
			upload();
			int id = -1;
			try {
				ArrayList<JournalEntity> jtmp = js.getAll();
				int max=0;
				for(int i=0;i<jtmp.size();i++){
					if(max<jtmp.get(i).getId()){
						max=jtmp.get(i).getId();
					}
				}
				id=max;
				id = jtmp.get(jtmp.size() - 1).getId();
				//System.out.println("id" + id);// ///////////////////////////
			} catch (RemoteException e) {
				// TODO Auto-generated catch block/
				e.printStackTrace();
			}
			FtPrintsService ft = client.getFtPrintsService();
			FtPrintEntity fpe = new FtPrintEntity(city, ue.getId(), id,
					routeList);

			try {
				ft.add(fpe);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			JOptionPane.showMessageDialog(null, "添加成功");
			ArrayList<JournalEntity> jelist = null;
			try {
				jelist = js.getByUser(ue.getId());
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Frame.removePane();
			try {
				Frame.addPane(new JournalListPane(jelist, ue));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
	}

	private File showPath() {
		/** */
		File f = null;
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);// 锟斤拷锟斤拷锟侥硷拷锟斤拷模式为锟斤拷锟斤拷锟侥硷拷
		int result = fileChooser.showOpenDialog(new javax.swing.JFrame());// 锟斤拷示锟皆伙拷锟斤拷
		if (result == JFileChooser.APPROVE_OPTION) { // 锟矫碉拷锟矫伙拷锟斤拷为
			f = fileChooser.getSelectedFile(); // 锟矫碉拷选锟斤拷锟斤拷募锟�
		}
		return f;

	}

	private void upload() {
		// String[] image = imagePath.toString().split(";");
		for (int i = 0; i < image.size(); i++) {
			try {
				tf.upLoadFile(image.get(i));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// System.out.println("the mp3  "+mp3Path.length());
		if (mp3Path.length() != 0) {
			try {
				tf.upLoadFile(new File(mp3Path.toString()));
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		if (rmvbPath.length() != 0) {
			try {
				tf.upLoadFile(new File(rmvbPath.toString()));
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		try {
			// System.out.println("get here ");
			js.addJournal(je);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/** input a route */
	}
}
